package cn.tedu._03vehicle.base.interceptors;

import cn.tedu._03vehicle.pojo.vo.UserVO;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * 登录状态校验的拦截器
 */
@Slf4j
public class LoginCheckInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.debug("进入到登录状态校验的拦截器...");
        /*
            1.获取会话对象:HttpSession;
              HttpSession session = request.getSession();
            2.从会话对象中获取用户标识;
            3.判断用户标识是否为null;
              3.1 为null,表示用户未登录;
                  方案1:抛出异常,再由全局异常处理器处理异常;
                  方案2:重定向到登录页面login.html,再return false;
                        response.sendRedirect("/login.html");
              3.2 不为null,则 return true; 放行
         */
        HttpSession session = request.getSession();
        UserVO userVO = (UserVO) session.getAttribute("user");
        if (userVO == null){ //未登录
            //重定向到登录页面:http://localhost:8080/login.html
            response.sendRedirect("/login.html");
            return false;
        }
        //登录状态正常,放行
        return true;
    }
}












